/*******************************************************************
 * Copyright (c) 2013 珠海比特讯科技有限公司. All rights reserved.
 * （1）软件的版权将受到法律保护，不允许非经授权的使用；
 * （2）未经版权所有人授权，任何人不得修改、复制和传播软件源代码、图片及其它资源等；
 * （3）未经版权所有人授权，不允许对软件进行修改；
 * （4）未经版权所有人授权，不允许在该软件的基础上开发新的软件；
 * （5）珠海比特讯科技有限公司拥有最终解释权
 *******************************************************************/
package youxiao.bytezon.controllers;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import youxiao.bytezon.models.Course;
import youxiao.bytezon.models.Teacher;
import youxiao.bytezon.repositories.CourseRepository;
import youxiao.bytezon.views.commons.PageListView;
import youxiao.bytezon.views.courses.CourseView;

@RestController
@RequestMapping("/courses")
public class CoursesController extends BaseController {
	
	@Autowired CourseRepository courseRepository;
	@Autowired EntityManager entityManager;
	
	@ResponseBody
	@RequestMapping(value = "", method = RequestMethod.GET)
	public PageListView<CourseView> index(HttpServletRequest request) {
		String pageNumStr = request.getParameter("page");
		int pageNum = pageNumStr == null? 0 : Integer.parseInt(pageNumStr) - 1;
		
		Teacher currentTeacher = this.getCurrentTeacher();
		
		Pageable pageable = new PageRequest(pageNum, 50);
		CriteriaBuilder cb = entityManager.getCriteriaBuilder();
		
    CriteriaQuery<Course> cq = cb.createQuery(Course.class);
    Root<Course> root = cq.from(Course.class);
    root.fetch("school");
    root.fetch("coursetype");
    cq.select(root)
    		.where(cb.equal(root.get("teacher"), currentTeacher))
			.orderBy(cb.desc(root.get("id")));
    
		List<Course> list = entityManager.createQuery(cq)
				.setFirstResult(pageable.getOffset())
				.setMaxResults(pageable.getPageSize())
				.getResultList();
		
		// query the count of users
		CriteriaQuery<Long> cqCount = cb.createQuery(Long.class);
		cqCount.select(cb.count(cqCount.from(Course.class)))
			.where(cb.equal(root.get("teacher"), currentTeacher));
		Long count = entityManager.createQuery(cqCount).getSingleResult();
		
		Page<Course> page = new PageImpl<Course>(list, pageable, count);
		
		return new PageListView<CourseView>(page, entry -> new CourseView(entry));
	}
	
	@ResponseBody
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	public CourseView detail(@PathVariable("id") Long id) {
		Course course = courseRepository.findOne(id);
		CourseView courseView = new CourseView(course, true);
		return courseView;
	}
	
}
